﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using PLM.ConfigurationCenter.Core.Util;
using SqlSugar;

namespace PLM.ConfigurationCenter.Service {
    public class Repository<T> : SimpleClient<T> where T : class, new() {
        public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
        {
            if (context == null) {
                Context = new SqlSugarClient(new ConnectionConfig() {
                    DbType = DbType.Sqlite,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    ConnectionString = CommonHandler.ConnectionString
                });

                Context.Aop.OnLogExecuting = (s, p) => {
                    Console.WriteLine(s);
                };
            }
        }

        /// <summary>
        /// 扩展方法，自带方法不能满足的时候可以添加新方法
        /// </summary>
        /// <returns></returns>
        public List<T> CommQuery(string json) {
            T t = Context.Utilities.DeserializeObject<T>(json);
            var list = Context.Queryable<T>().WhereClass(t).ToList();
            return list;
        }
        /// <summary>
        /// 扩展方法，自带方法不能满足的时候可以添加新方法
        /// </summary>
        /// <returns></returns>
        public List<T> CommQuery() {
            var list = Context.Queryable<T>().ToList();
            return list;
        }
        /// <summary>
        /// 扩展方法，自带方法不能满足的时候可以添加新方法
        /// </summary>
        /// <returns></returns>
        public List<T> CommQuery(Expression<Func<T, bool>> expression) {
            var list = Context.Queryable<T>().Where(expression).ToList();
            return list;
        }
    }
}
